import threading
import time
import os
import sys
import cv2
import subprocess
from cv2 import VideoWriter,VideoWriter_fourcc,imread,resize
from PIL import Image, ImageFont, ImageDraw ,ImageTk

ascii_char = list("$B%314567890*WM#oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:oa+>!:+. ")
res=os.path.dirname(os.path.abspath(__file__))
base_path=os.path.dirname(os.path.dirname(res))
sys.path.insert(0,base_path)
# os.environ['PATH']+=os.pathsep+path1
# # print(os.environ['PATH'])

#为避免在下载时tkinter界面卡死，创建线程函数
def thread_it(func, *args):
    # 创建
    t = threading.Thread(target=func, args=args)
    # 守护 !!!
    t.setDaemon(True)
    # 启动
    t.start()


#将像素点转换为ascii码
def get_char(r,g,b,alpha = 256):
    if alpha == 0:
        return ''
    length = len(ascii_char)
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
    unit = (256.0+1)/length
    return ascii_char[int(gray/unit)]


semaphore = threading.Semaphore(10)
def txt2imageThread(file_name,color_radio,scale_scale):
    try:
        semaphore.acquire()
        print("开始处理ASCII图片" + file_name)
        im = Image.open(file_name).convert('RGB')
        im_width=im.width
        im_height=im.height
        # im=im.resize((int(im.width/100*scale_scale),int(im.height/100*scale_scale)),Image.NEAREST)
        # gif拆分后的图像，需要转换，否则报错，由于gif分割后保存的是索引颜色
        raw_width = im.width
        raw_height = im.height
        width = int(raw_width/6)
        height = int(raw_height/15)
        im = im.resize((width,height),Image.NEAREST)

        txt=""
        colors = []
        for i in range(height):
            for j in range(width):
                pixel = im.getpixel((j,i))
                if(color_radio==1):
                    colors.append((pixel[0],pixel[1],pixel[2]))
                else:
                    colors.append((0,0,0))
                if(len(pixel) == 4):
                    txt += get_char(pixel[0],pixel[1],pixel[2],pixel[3])
                else:
                    txt += get_char(pixel[0],pixel[1],pixel[2])
            txt += '\n'
            colors.append((255,255,255))

        im_txt = Image.new("RGB",(raw_width,raw_height),(255,255,255))
        dr = ImageDraw.Draw(im_txt)
        # font = ImageFont.truetype(os.path.join("fonts","timesbi.ttf"),12)
        font=ImageFont.load_default().font

        x=y=0
        #获取字体的宽高
        font_w,font_h=font.getsize(txt[1])
        font_h *= 1.37 #调整后更佳
        #ImageDraw为每个ascii码进行上色
        for i in range(len(txt)):
            if(txt[i]=='\n'):
                x+=font_h
                y=-font_w
            dr.text((y,x),txt[i], fill = colors[i])
            y+=font_w

        name = file_name
        im_txt=im_txt.resize((im_width,im_height),Image.NEAREST)
        im_txt.save(name)
    finally:
        semaphore.release()

#将视频拆分成图片
def video2txt_jpg(colorClass,scaleClass):
    # file_name = "D:\\视频输出\\马赛克版本绝命毒师，say my name.mp4"
    if not os.path.exists('Cache'):
        print("不存在Cache目录，退出")
        return
    os.chdir('Cache')

    for file in os.listdir(os.getcwd()):
        t = threading.Thread(target=txt2imageThread, args=(file,float(colorClass),float(scaleClass)))
        t.start()

    for t in threading.enumerate():
        if t is not threading.current_thread():
            t.join()

    print("处理完毕ASCII图片")
    os.chdir('..')

#将图片合成视频

#递归删除目录
def remove_dir(path):
    if os.path.exists(path):
        if os.path.isdir(path):
            dirs = os.listdir(path)
            for d in dirs:
                if os.path.isdir(path+'/'+d):
                    remove_dir(path+'/'+d)
                elif os.path.isfile(path+'/'+d):
                    os.remove(path+'/'+d)
            os.rmdir(path)
            return
        elif os.path.isfile(path):
            os.remove(path)
        return
if __name__ == '__main__':
    colorOperator = sys.argv[1] #彩色1，黑白2
    scaleClass = sys.argv[2] #压缩级别
    print(colorOperator)
    print(scaleClass)
    video2txt_jpg(colorOperator,scaleClass)

